"""
Verify that workspace_id is required for all knowledge base APIs
Test that ValueError is raised when workspace_id is not provided
"""
import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.llm.hiagent_app.services.knowledge_service import KnowledgeService


def test_create_dataset_requires_workspace_id():
    """Test create_dataset requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.create_dataset(
            name="Test KB",
            description="Test",
            workspace_id=None  # Should fail
        )
        print("[FAIL] create_dataset should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] create_dataset requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_list_datasets_requires_workspace_id():
    """Test list_datasets requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.list_datasets(
            workspace_id=None  # Should fail
        )
        print("[FAIL] list_datasets should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] list_datasets requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_get_dataset_requires_workspace_id():
    """Test get_dataset requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.get_dataset(
            dataset_id="test_id",
            workspace_id=None  # Should fail
        )
        print("[FAIL] get_dataset should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] get_dataset requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_update_dataset_requires_workspace_id():
    """Test update_dataset requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.update_dataset(
            dataset_id="test_id",
            workspace_id=None,  # Should fail
            name="New Name"
        )
        print("[FAIL] update_dataset should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] update_dataset requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_delete_dataset_requires_workspace_id():
    """Test delete_dataset requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.delete_dataset(
            dataset_id="test_id",
            workspace_id=None  # Should fail
        )
        print("[FAIL] delete_dataset should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] delete_dataset requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_create_document_requires_workspace_id():
    """Test create_document requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.create_document(
            dataset_id="test_id",
            name="test.txt",
            workspace_id=None,  # Should fail
            file_url="test_url"
        )
        print("[FAIL] create_document should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] create_document requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_list_documents_requires_workspace_id():
    """Test list_documents requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.list_documents(
            dataset_id="test_id",
            workspace_id=None  # Should fail
        )
        print("[FAIL] list_documents should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] list_documents requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_delete_document_requires_workspace_id():
    """Test delete_document requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.delete_document(
            document_id="test_id",
            workspace_id=None  # Should fail
        )
        print("[FAIL] delete_document should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] delete_document requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_query_knowledge_requires_workspace_id():
    """Test query_knowledge requires workspace_id"""
    service = KnowledgeService()

    try:
        # Should raise ValueError
        service.query_knowledge(
            dataset_id="test_id",
            query="test",
            workspace_id=None  # Should fail
        )
        print("[FAIL] query_knowledge should require workspace_id")
        return False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] query_knowledge requires workspace_id")
            return True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            return False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        return False


def test_qa_dataset_requires_workspace_id():
    """Test QA dataset operations require workspace_id"""
    service = KnowledgeService()

    # Test create_qa_dataset
    try:
        service.create_qa_dataset(
            name="Test QA",
            description="Test",
            workspace_id=None  # Should fail
        )
        print("[FAIL] create_qa_dataset should require workspace_id")
        result1 = False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] create_qa_dataset requires workspace_id")
            result1 = True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            result1 = False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        result1 = False

    # Test list_qa_datasets
    try:
        service.list_qa_datasets(
            workspace_id=None  # Should fail
        )
        print("[FAIL] list_qa_datasets should require workspace_id")
        result2 = False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] list_qa_datasets requires workspace_id")
            result2 = True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            result2 = False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        result2 = False

    return result1 and result2


def test_term_dataset_requires_workspace_id():
    """Test term dataset operations require workspace_id"""
    service = KnowledgeService()

    # Test create_term_dataset
    try:
        service.create_term_dataset(
            name="Test Term",
            description="Test",
            workspace_id=None  # Should fail
        )
        print("[FAIL] create_term_dataset should require workspace_id")
        result1 = False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] create_term_dataset requires workspace_id")
            result1 = True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            result1 = False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        result1 = False

    # Test list_term_datasets
    try:
        service.list_term_datasets(
            workspace_id=None  # Should fail
        )
        print("[FAIL] list_term_datasets should require workspace_id")
        result2 = False
    except ValueError as e:
        if "workspace_id is required" in str(e):
            print("[PASS] list_term_datasets requires workspace_id")
            result2 = True
        else:
            print(f"[FAIL] Wrong error message: {e}")
            result2 = False
    except Exception as e:
        print(f"[FAIL] Unexpected error: {e}")
        result2 = False

    return result1 and result2


def main():
    """Run all tests"""
    print("=" * 60)
    print("Testing workspace_id Required for Knowledge APIs")
    print("=" * 60)
    print()

    tests = [
        ("Create Dataset", test_create_dataset_requires_workspace_id),
        ("List Datasets", test_list_datasets_requires_workspace_id),
        ("Get Dataset", test_get_dataset_requires_workspace_id),
        ("Update Dataset", test_update_dataset_requires_workspace_id),
        ("Delete Dataset", test_delete_dataset_requires_workspace_id),
        ("Create Document", test_create_document_requires_workspace_id),
        ("List Documents", test_list_documents_requires_workspace_id),
        ("Delete Document", test_delete_document_requires_workspace_id),
        ("Query Knowledge", test_query_knowledge_requires_workspace_id),
        ("QA Dataset Operations", test_qa_dataset_requires_workspace_id),
        ("Term Dataset Operations", test_term_dataset_requires_workspace_id),
    ]

    passed = 0
    failed = 0

    for name, test_func in tests:
        print(f"\nTesting: {name}")
        print("-" * 60)
        try:
            if test_func():
                passed += 1
            else:
                failed += 1
        except Exception as e:
            print(f"[ERROR] Test crashed: {e}")
            failed += 1

    print("\n" + "=" * 60)
    print(f"Test Summary: {passed} passed, {failed} failed")
    print("=" * 60)

    if failed == 0:
        print("\nAll tests passed! workspace_id is required for all knowledge APIs")
        return 0
    else:
        print(f"\n{failed} test(s) failed!")
        return 1


if __name__ == "__main__":
    exit(main())
